package com.framework.bdf4j.annotations;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.ApplicationEventPublisher;

import com.framework.bdf4j.comm.Constants;
import com.framework.bdf4j.comm.web.WebUtil;
import com.framework.bdf4j.event.SysLogEvent;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * 操作日志使用spring event异步入库
 *
 */
@Slf4j
@Aspect
@AllArgsConstructor
public class SysLogAspect {
	private final ApplicationEventPublisher publisher;

	@SneakyThrows
	@Around("@annotation(sysLog)")
	public Object around(ProceedingJoinPoint point, SysLog sysLog) {
		String strClassName = point.getTarget().getClass().getName();
		String strMethodName = point.getSignature().getName();
		log.debug("[类名]:{},[方法]:{}", strClassName, strMethodName);

		com.framework.bdf4j.sysadm.entity.SysLog logvo = new com.framework.bdf4j.sysadm.entity.SysLog();
		logvo.setTitle(sysLog.value());
        HttpServletRequest request = WebUtil.getRequest();
        logvo.setCreateBy(WebUtil.getHttpCurrentUserName());
        logvo.setType(Constants.STATUS_NORMAL);
        logvo.setRemoteAddr(WebUtil.getHost());
        logvo.setRequestUri(URLUtil.getPath(request.getRequestURI()));
        logvo.setMethod(request.getMethod());
        logvo.setUserAgent(request.getHeader("user-agent"));
        logvo.setParams(HttpUtil.toParams(request.getParameterMap()));
        logvo.setServiceId("");

        Long startTime = System.currentTimeMillis();
        Object obj = point.proceed();
        Long endTime = System.currentTimeMillis();
        Long during = endTime - startTime;
        logvo.setTime(during.intValue());
        publisher.publishEvent(new SysLogEvent(logvo));
        return obj;	
	}

}
